<script setup>
import {ref, onMounted, computed} from 'vue'
import { selExamsApi, oneExamLogApi, pageExamLogsApi } from '@/commons/api'
import Loader from '@/components/loader/Loader.vue'
import Selector from '@/components/select/Selector.vue'
import { CScrollbar } from 'c-scrollbar'
import Pager from '@/components/pager/Pager.vue'
import { formatDatetime } from '@/commons/filter'
import Msg from '@/components/message'
import axios from 'axios'

const loadShow = ref(false)

// 界面挂载前处理
onMounted(() => {
  // 下拉选择试卷列表
  selExams()
})

const examList = ref([])
const selExams = async () => {
  const res = await selExamsApi()
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    examList.value = res.data
    // 列表展示
    await page(0, 1)
  }
}

const schRef = ref({
  examId: '',
  keywords: '',
  offset: 0,
  limit: 20
})
const total = ref(0)
const curPage = ref(1)
const logList = ref([])
const hasData = ref(false)
// page 列表展示
const page = async (offset, cur) => {
  schRef.value.offset = offset || 0
  curPage.value = cur || 1
  hasData.value = false
  const res = await pageExamLogsApi(schRef.value)
  if(res.code === import.meta.env.VITE_SUCCESS_CODE && res.data) {
    hasData.value = true
    total.value = res.data.total
    logList.value = res.data.list
  }
}

// search 筛选
const schShow = ref(false)
const search = () => {
  schShow.value = !schShow.value
}

// clrSch 重置搜索框
const clrSch = () => {
  schRef.value = {
    examId: '',
    keywords: '',
    offset: 0,
    limit: 20
  }
  page(0, 1)
}

const modalShow = ref(false)
const logRef = ref({})
const detail = async (logId) => {
  modalShow.value = true
  const res = await oneExamLogApi({ logId })
  if(res.code === import.meta.env.VITE_SUCCESS_CODE) {
    logRef.value = res.data
    let m = 1
    logRef.value.qstList.forEach(cur => {
      cur.qstNo = cur.kind===6 ? m : cur.qstNo
      let n = 1
      cur.score = 0
      cur.optList.forEach(opt => {
        opt.optNo = cur.kind===6 ? m + '.' + n : opt.optNo
        n++
        if(opt.score > 0) {
          cur.score = opt.score
        }
      })
      m++
      const imgNames = cur.fileNames ? cur.fileNames.split(',') : []
      const imgUrls = cur.fileUrls ? cur.fileUrls.split(',') : []
      cur.imgList = []
      for(let i=0; i<imgNames.length; i++) {
        cur.imgList.push({ name: imgNames[i], url: imgUrls[i] })
      }
    })
  } else {
    Msg({ kind: 'error', txt: res.msg})
  }
}

// exportLog 导出
const exportLog = async (logId) => {
  // axios.post('http://127.0.0.1:8010/exam/log/export', { logId }, { responseType: 'blob' }).then(res => {
  axios.post('http://sc-api.haobing.pw/exam/log/export', { logId }, { responseType: 'blob' }).then(res => {
    let aTag = document.createElement('a')
    aTag.href = window.URL.createObjectURL(new Blob([res.data]))
    aTag.download = decodeURI(res.headers['content-disposition'].split('=')[1].replace(' ', ''))
    aTag.click()
    window.URL.revokeObjectURL(aTag.href)
  }).catch(function (err) {
    Msg({kind: 'error', txt: err})
  })
}

// closeModal 关闭弹出层，并重置表单数据
const closeModal = () => {
  modalShow.value = false
}

// fmtDate 时间戳转时间
const fmtDate = computed(() => {
  return (time) => {
    let date = new Date(time*1000)
    return formatDatetime(date)
  }
})

const setValue = (item, kind) => {
  switch(kind) {
    case 1:
      schRef.value.examId = item.selId
      schRef.value.title = item.selName
      break
  }
}

const fmtKind = computed(() =>{
  return (kind) => {
    switch (kind) {
      case 1:
        return '单选题'
      case 2:
        return '判断题'
      case 3:
        return '多选题'
      case 4:
        return '填空题'
      case 5:
        return '简答题'
      case 6:
        return '实操题'
      default:
        return '其它'
    }
  }
})

const picShow = ref(false)
const imgRef = ref({ name: '', url: '' })
const showPic = (name, url) => {
  imgRef.value.name = name
  imgRef.value.url = url
  picShow.value = true
}

const closePicShow = () => {
  picShow.value = false
}
</script>

<template>
  <div class="el-a">
    <div class="el-b">
      <div class="el-c">
        <div class="btn-r mr15" title="筛选" @click="search"><i class="iconfont">&#xea49;</i></div>
        <div class="btn-r mr15" title="刷新" @click="page(0, 1)"><i class="iconfont">&#xea8c;</i></div>
      </div>
      <div class="el-d"><i class="iconfont">&#xeaaa;</i> 当前位置：工作台 > 试卷管理 > 答题记录</div>
    </div>
    <div v-show="schShow" class="el-e">
      <div class="mr15 mt10"><selector :kind="1" :sel-list="examList" :inboxed="true" :cur-name="schRef.title ? schRef.title : ''" pre-name="试卷" @setValue="setValue" /></div>
      <div class="mr15 mt10"><input type="text" v-model="schRef.keywords" maxlength="30" placeholder="请输入关键字" class="sch-ipt" /></div>
      <div class="el-f mt10">
        <div class="btn-pi mr15" title="搜索" @click="page(0, 1)"><i class="iconfont">&#xea8e;</i> 搜索</div>
        <div class="btn-d" title="重置" @click="clrSch"><i class="iconfont">&#xea4f;</i> 重置</div>
      </div>
    </div>
    <div v-if="hasData">
      <table>
        <tbody>
        <tr>
          <th style="width: 20%;">员工</th>
          <th style="width: 30%;">试卷</th>
          <th style="width: 10%;">分数</th>
          <th style="width: 20%;">答题时间</th>
          <th style="width: 10%;">答题时长</th>
          <th style="width: 10%;">操作</th>
        </tr>
        <tr v-for="log in logList" :key="log.logId" class="tr-style">
          <td class="txt-center"> {{ log.realName }}[{{ log.mobile }}]({{ log.workNo }})</td>
          <td class="cl-blue" @click="detail(log.logId)">{{ log.title }}</td>
          <td class="txt-right">{{ log.score }}分</td>
          <td class="txt-center">{{ fmtDate(log.addTime) }}</td>
          <td class="txt-right">{{ log.testTime>60 ? Number(log.testTime / 60).toFixed(0)+'分钟' : log.testTime+'秒' }}</td>
          <td class="txt-center">
            <span class="cl-blue" title="导出" @click="exportLog(log.logId)"><i class="iconfont">&#xeaa9;</i> 导 出</span>
          </td>
        </tr>
        </tbody>
      </table>
      <pager v-if="hasData" :limit="schRef.limit" :total="total" :page="curPage" @turn="page" />
    </div>
    <div v-else class="no-data">暂无内容</div>

    <!-- 详情弹出层 -->
    <transition name="fade-mod" appear>
      <div v-if="modalShow" class="modal-backdrop">
        <c-scrollbar>
          <div class="modal" style="width: 900px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont">&#xea54;</i> 试卷信息</div>
              <div class="header-right" @click="closeModal"><i class="iconfont fs22">&#xea7f;</i></div>
            </div>
            <div class="modal-body">
              <div>
                <div class="qst-a">
                  <div class="qst-b">{{ logRef.title }}</div>
                  <div class="qst-c txt-center">时长：{{ logRef.examTime }}分钟 总分：{{ logRef.score }}分 得分：{{ logRef.myScore }}分</div>
                </div>
                <div class="qst-d" v-for="(qst, index) in logRef.qstList" :key="qst.qstId">
                  <div class="qst-e">{{ index + 1 }}. 【{{ fmtKind(qst.kind) }}】{{ qst.title }}({{ qst.keywords }})({{ qst.score }}分)</div>
                  <div v-for="img in qst.imgList" @click="showPic(img.name, img.url)"><img :alt="img.name" v-lazy="img.url" class="qst-g" /></div>
                  <div v-if="qst.kind===1 || qst.kind===2 || qst.kind===3">
                    <div class="qst-h" v-for="opt in qst.optList" :key="opt.optId">
                      <div :class="['qst-i', opt.myAnswer && opt.myAnswer.indexOf(opt.optId)!==-1 ? 'color-p' : '']" class="qst-i">{{ opt.optNo }}. {{ opt.optName }}</div>
                    </div>
                  </div>
                  <div v-if="qst.kind===4 || qst.kind===5">
                    <div class="qst-h" v-for="opt in qst.optList" :key="opt.optId">
                      <div class="qst-i">{{ opt.optNo }}. {{ opt.optName }}</div>
                      <div :class="['qst-i', opt.score>0 ? 'color-s' : 'color-e']">{{ opt.answer }}</div>
                    </div>
                  </div>
                  <div v-if="qst.kind===6">
                    <div class="test-k" v-for="opt in qst.optList" :key="opt.optId">
                      <div class="log-k">{{ opt.optNo }}.1. 风险点</div>
                      <div class="log-l">{{ opt.fxd }}</div>
                      <div class="log-l" v-if="opt.fxdKey">命中关键词：<span class="tag-p mr15" v-for="key in opt.fxdKey.split('@-@')" :key="key">{{ key }}</span></div>
                      <div class="log-k">{{ opt.optNo }}.2. 事故类型</div>
                      <div class="log-l">{{ opt.sglx }}</div>
                      <div class="log-l" v-if="opt.sglxKey">命中关键词：<span class="tag-p mr15" v-for="key in opt.sglxKey.split('@-@')" :key="key">{{ key }}</span></div>
                      <div class="log-k">{{ opt.optNo }}.3. 防范措施</div>
                      <div class="log-l">{{ opt.ffcs }}</div>
                      <div class="log-l" v-if="opt.ffcsKey">命中关键词：<span class="tag-p mr15" v-for="key in opt.ffcsKey.split('@-@')" :key="key">{{ key }}</span></div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="modal-footer">
              <div class="btn-d" @click="closeModal"><i class="iconfont">&#xea4f;</i> 关闭</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>

    <transition name="fade-mod" appear>
      <div v-show="picShow" class="modal-backdrop">
        <c-scrollbar>
          <div class="modal" style="width: 1100px;">
            <div class="modal-header">
              <div class="header-left"><i class="iconfont">&#xea54;</i> 图片详情</div>
              <div class="header-right" @click="closePicShow"><i class="iconfont fs20">&#xea7f;</i></div>
            </div>
            <div class="modal-body">
              <div><img :alt="imgRef.name" v-lazy="imgRef.url" class="w100" /></div>
            </div>
            <div class="modal-footer">
              <div class="btn-d up-o" @click="closePicShow"><i class="iconfont">&#xea4f;</i> 关闭</div>
            </div>
          </div>
        </c-scrollbar>
      </div>
    </transition>
    <loader :loadShow="loadShow" />
  </div>
</template>

<style scoped>
.el-a {padding: 10px;}
.el-b {padding: 0 20px 10px 20px; display: flex; display: -webkit-flex;}
.el-c {display: inline-flex; display: -webkit-inline-flex;}
.el-d {flex-grow: 1; text-align: right; padding-top: 10px; color: #666;}
.el-e {border: 1px dashed #DDD; padding: 5px 15px 15px 15px; display: flex; display: -webkit-flex; flex-wrap: wrap; margin-bottom: 10px;}
.el-f {display: inline-flex; display: -webkit-inline-flex;}
.qst-a {}
.qst-b {font-size: 18px; text-align: center; padding: 20px 0;}
.qst-c {text-align: center; padding-bottom: 20px; border-bottom: 1px #CCC solid;}
.qst-d {margin: 15px 0; padding: 10px 0;}
.qst-e {padding: 10px 0; font-size: 15px;}
.qst-g {width: 100%;}
.qst-h {padding: 10px 20px;}
.qst-i {line-height: 30px;}
.test-k {padding: 0.6rem 0; border-bottom: 1px solid #CCC;}
.log-k {color: #18a058;}
.log-l {margin-bottom: 0.6rem;}
</style>